package org.amos.tenant;


import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import org.amos.tenant.aspect.TenantIgnoreAspect;
import org.amos.tenant.core.CustomTenantLineHandler;
import org.amos.tenant.core.TenantApi;
import org.amos.tenant.core.TenantFilter;
import org.amos.tenant.properties.TenantProperties;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

import java.util.ArrayList;
import java.util.List;

@AutoConfiguration
@EnableConfigurationProperties(TenantProperties.class)
@ConditionalOnProperty(prefix = TenantProperties.PREFIX, value = "enabled", matchIfMissing = true)
public class TenantAutoConfiguration {
    @Bean
    public TenantIgnoreAspect tenantExcludeAspect() {
        return new TenantIgnoreAspect();
    }

    @Bean
    public TenantLineInnerInterceptor tenantLineInnerInterceptor(MybatisPlusInterceptor interceptor, TenantProperties properties) {
        TenantLineInnerInterceptor tenantLineInnerInterceptor = new TenantLineInnerInterceptor(new CustomTenantLineHandler(properties));
        List<InnerInterceptor> innerInterceptors = new ArrayList<>(interceptor.getInterceptors());
        // 如果用了分页插件注意先 add TenantLineInnerInterceptor 再 add PaginationInnerInterceptor
        innerInterceptors.add(0, tenantLineInnerInterceptor);
        interceptor.setInterceptors(innerInterceptors);
        return tenantLineInnerInterceptor;
    }

    @Bean
    public FilterRegistrationBean<TenantFilter> tenantFilter(TenantProperties properties, TenantApi tenantApi) {
        FilterRegistrationBean<TenantFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new TenantFilter(properties, tenantApi));
        registrationBean.setOrder(-90);
        return registrationBean;
    }
}
